<?php

namespace App\Http\Controllers\Admin;


use Validator;
use Illuminate\Http\Request;
use App\Model\AdminLogsModel;
use App\Model\ShopAttrValModel;
use App\Model\ShopAttrKeyModel;
use App\Model\ShopAttrTkvModel;
use App\Model\ShopAttrTypeModel;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class ShopAttrTypeController extends Controller
{	

	//列表页
    public function index(Request $request)
    {
    	$list = ShopAttrTypeModel::where(function ($query) {
		  if (request()->keywords) {
			  $query->where('tname', "like", "%".request()->keywords ."%");
		  }
	  	})
		  ->orderBy('id', 'desc')
		  ->paginate(10);
    	foreach($list as $k=>$v){
    		$list[$k]['attrname'] = trim(ShopAttrTypeModel::attrname($v['id']),',');
		}
	  	$pageParam['keywords'] = $request->input('keywords');

       	$page = $list->appends($pageParam)->links();
       	foreach($list as $v){
       		

       	}
      	return view('admin.attr_type.index',compact('list','page','request'));
    }

    //加载添加页
    public function add()
    {
    	return view('admin.attr_type.add');
    }

    //添加
    public function insert(Request $request)
    {	
    	$post = $request->post();
	  	$validator = Validator::make($post,[
			'tname'=>'required|unique:shop_attr_type,tname',
		  
	  	],[
			'tname.required' => '规格类型不能为空',
			'tname.unique' => '规格类型已存在',
		 
	  	]);
	  	if($validator->fails()){
			return returnJson(0, $validator->errors()->first());
	  	}

	  	DB::beginTransaction();
	  	try {
			$attrtype = New ShopAttrTypeModel();
			$attrtype -> tname = request() -> tname;
			$attrtype -> save();
			$msg = '添加规格类型【'.request()->tname.'】(id:'.$attrtype->id.')';
			AdminLogsModel::addLog($msg);
			DB::commit();
	  	} catch (Exception $e) {
			DB::rollBack();
			throw $e;
			return returnJson(0,'操作失败,请稍后再试');
	  	}
	  	return returnJson(1,'添加成功');
    }

    //编辑页面
	public function edit(Request $request)
	{
  	    $list = ShopAttrTypeModel::where('id',request()->id)->first();
  	    return view('admin.attr_type.edit',compact('list'));
	}

	//修改
	public function update(Request $request)
	{
		$post = $request->post();
	  	$validator = Validator::make($post,[
			'tname'=>'required|unique:shop_attr_type,tname',
		  
	  	],[
			'tname.required' => '规格类型不能为空',
			'tname.unique' => '规格类型已存在',
		 
	  	]);
	  	if($validator->fails()){
			return returnJson(0, $validator->errors()->first());
	  	}

	  	if(ShopAttrTypeModel::where('id',$post['id'])->update(['tname'=>request()->tname])){
			$msg = '编辑规格类型【'.request()->tname.'】(id:'.$post['id'].')';
			AdminLogsModel::addLog($msg);
			return returnJson(1, '修改成功');
		}else{
			return returnJson(0, '修改失败');
		}

	}

	//为规格类型添加规格名
	public function add_xzattr(Request $request)
	{
		$attr_type_id=$request->id;

		$attr_type_name=ShopAttrTypeModel::where('id',$attr_type_id)->first();	//规格类型名称
		$yxz_attr_key=ShopAttrTypeModel::with('attrkey')->find($attr_type_id);
		//dd($yxz_attr_key->attrkey);
		$yxzlist=array();
		foreach($yxz_attr_key->attrkey as $attrkey){
			//如果已将存在就不往里面添加
			// print_r($specifications);
			//已选中的规格(颜色....)
        	if(!in_array($attrkey,$yxzlist)){
        		array_push($yxzlist,$attrkey);
        	}
		}

		$kids="";
		$kidss=array();
		foreach($yxzlist as $k=>$v){
			$kids.=$v->pivot->Kid.',';
			array_push($kidss,$v->pivot->Kid);
			$values = ShopAttrValModel::where('attr_key_id',$v->pivot->Kid)->get();

			foreach($values as $vk=>$vv){
            	//属性是否已选中
            	$is_xz = ShopAttrTkvModel::where('tid',$v->pivot->tid)->where('kid',$v->pivot->Kid)->where('vid',$vv->id)->first();
            	if($is_xz){
                    //已选中
                    $values[$vk]['is_xz'] = 1;
                }else{
                    //未选中
                    $values[$vk]['is_xz'] = 2;
                }
                
            }
            $yxzlist[$k]['info'] = $values;

		}

		//dd($yxzlist);

		//未选中的规格
    	$wxzlist = ShopAttrKeyModel::whereNotIn('id',$kidss)->get();
    	//dd($wxzlist);
    	return view('admin.attr_type.xz_attr')->with(['attr_type_name'=>$attr_type_name,'yxzlist'=>$yxzlist,'wxzlist'=>$wxzlist]);
	}

	//查看选择规格的属性(前端效果为选择时弹出相应的属性)
    public function xzattr_value(Request $request){
    	// $all = $request->all();
    	$kid = $request->get('kid',null);
    	//return $kid;
    	if(empty($kid)){
//    		return $this->errors('参数错误');
    		return returnJson(0,'参数错误');
    	}
    	$list = ShopAttrValModel::where('attr_key_id',$kid)->get();//属性信息
        return returnJson(1,'操作成功',$list);
    }

    //为规格类型(连衣裙)添加新的规格带属性(尺寸21寸)
    public function insert_xzattr(Request $request){
    	$name = $request->get('name',null);
    	//return response()->json(['code'=>200,'data'=>'操作成功','tid'=>$tid]);
    	if(empty($name)){
    		return returnJson(0, '请选择属性');
    	}
    	$tid = $request->get('tid',null);
    	$kid = $request->get('kid',null);

    	//规格类型名称
		$type = ShopAttrTypeModel::where('id',$tid)->first();
    	DB::beginTransaction();
    	try{
    		foreach ($name as $v) {
	    		$attr_type = new ShopAttrTkvModel();
	    		$data['tid'] = $tid;
	    		$data['Kid'] = $kid;
	    		$data['vid'] = $v;
	    		$attr_type->insert($data);
	    	}
	    	DB::commit();
			$msg = '规格类型【'.$type['tname'].'】(id:'.$type['id'].')添加属性';
			AdminLogsModel::addLog($msg);
	    	return returnJson(1,'操作成功');
    	}catch(\Exception $exception){
    		DB::rollBack();
			return returnJson(0,'操作失败,请稍后再试');
    	}
    	
    }

    public function update_xzattr(Request $request)
    {
    	$tid = $request->get('tid',null);
    	$name = $request->get('name',null);
        // dd($name);
        DB::beginTransaction();
    	try {
    		//先删除之前全部的(规格带有的属性)
	    	ShopAttrTkvModel::where('tid',$tid)->delete();
	    	if(!empty($name)){
	    		foreach ($name as $v) {
		    		$str = explode('-', $v);
		    		$attr_tkv = new ShopAttrTkvModel();
		    		$attr_tkv->tid = $tid;
		    		$attr_tkv->kid = $str['0'];
		    		$attr_tkv->vid = $str['1'];
		    		$attr_tkv->save();
	    		}
	    	}
	    	DB::commit();
			$msg = '规格类型【'.$type['tname'].'】(id:'.$type['id'].')编辑属性';
			AdminLogsModel::addLog($msg);
	    	return returnJson(1,'操作成功');
    	}catch(\Exception $exception){
    		DB::rollBack();
			return returnJson(0,'操作失败,请稍后再试');
    	}

    }
}
